class RestaurantsController < ApplicationController
  # GET /restaurants
  # GET /restaurants.xml
  def index
    @restaurants = Restaurant.find(:all)
    
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @restaurants }
    end
  end
  
  # GET /restaurants/1
  # GET /restaurants/1.xml
  def show
    @restaurant = Restaurant.find(params[:id])
    
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @restaurant }
    end
  end
  
  # GET /restaurants/new
  # GET /restaurants/new.xml
  def new
    @restaurant = Restaurant.new
    @product_categories = ProductCategory.find(:all)
    
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @restaurant }
    end
  end
  
  # GET /restaurants/1/edit
  def edit
    @product_categories = ProductCategory.find(:all)
    @restaurant = Restaurant.find(params[:id])
  end
  
  # POST /restaurants
  # POST /restaurants.xml
  def create
    params[:restaurant][:product_category_ids] ||= []
    @restaurant = Restaurant.new(params[:restaurant])
    @restaurant.user = current_user
    @product_categories = ProductCategory.find(:all)
    
    respond_to do |format|
      begin
        Restaurant.transaction do
          @restaurant.save!
          flash[:notice] = 'Restaurant was successfully created.'
          format.html { redirect_to(@restaurant) }
          format.xml  { render :xml => @restaurant, :status => :created, :location => @restaurant }
        end
        rescue
        format.html { render :action => "new" }
        format.xml  { render :xml => @restaurant.errors, :status => :unprocessable_entity }
      end
    end
  end
  
  # PUT /restaurants/1
  # PUT /restaurants/1.xml
  def update
    params[:restaurant][:product_category_ids] ||= []
    @restaurant = Restaurant.find(params[:id])
    @product_categories = ProductCategory.find(:all)
    
    respond_to do |format|
      begin
        Restaurant.transaction do
          @restaurant.update_attributes!(params[:restaurant])
          flash[:notice] = 'Restaurant was successfully updated.'
          format.html { redirect_to(@restaurant) }
          format.xml  { head :ok }
        end
        rescue ActiveRecord::RecordInvalid
        format.html { render :action => "edit" }
        format.xml  { render :xml => @restaurant.errors, :status => :unprocessable_entity }
      end
    end
  end
  
  # DELETE /restaurants/1
  # DELETE /restaurants/1.xml
  def destroy
    @restaurant = Restaurant.find(params[:id])
    @restaurant.destroy
    
    respond_to do |format|
      format.html { redirect_to(restaurants_url) }
      format.xml  { head :ok }
    end
  end
end
